const { MayBe, Container } = require('./support')
const fp = require('lodash/fp')

// 练习1：使用fp.add(x, y) 和 fp.map(f, x) 创建一个能让functor里的值增加的函数ex1

let maybe = MayBe.of([5, 6, 1])

let ex1 = () => {
    return maybe.map(fp.map(fp.add(1)))
}

// console.log(ex1())


// 练习2：实现一个函数ex2，能够使用fp.first()获取列表的第一个元素

let xs = Container.of(['do', 'ray', 'me', 'fa', 'so', 'la', 'ti', 'do'])

let ex2 = () => {
    return xs.map(fp.first)._value
}

// console.log(ex2())

// 练习3：实现一个函数ex3，使用safeProp和fp.first找到user的名字的首字母

let safeProp = fp.curry(function (x, o) {
    return MayBe.of(o[x])
})

let user = { id: 2, name: 'Albert' }

let ex3 = () => {
    return safeProp('name')(user).map(fp.first)._value
}

// console.log(ex3())


// 练习4：使用MayBe重写ex4，不要有if语句

let ex4 = function (n) {
    if (n) {
        return parseInt(n)
    }
}

let ex4_ = function (n) {
    // isNothing 与 if(n) 判断的差异，纯用MayBe达不到一致效果
    // 用三元表达式似乎又没意义，和用if有什么差别呢？
    return !!n? parseInt(MayBe.of(n)._value) : undefined
}

console.log(ex4(1), ex4_(1))
console.log(ex4('1'), ex4_('1'))
console.log(ex4(0), ex4_(0))
console.log(ex4('0'), ex4_('0'))
console.log(ex4(null), ex4_(null))
console.log(ex4(undefined), ex4_(undefined))
console.log(ex4(''), ex4_(''))
console.log(ex4('s'), ex4_('s'))
